import { createStore } from "vuex";
import { getChannels } from "@/api/channel.js";
import * as goodsApi from "@/api/goods.js";
import persistedState from "vuex-persistedstate";

import user from "./user.js"

export default createStore({
    state: {
        channels: [],
        goods: [], //[]
        pageSize: 25,
        goodsLoading: false,
    },
    getters: {
        getGoodsByPageSync: (state) => (page) => {
            return state.goods.slice(
                state.pageSize * (page - 1),
                state.pageSize * page
            );
        },
    },
    mutations: {
        setChannels(state, arr) {
            state.channels = arr;
        },
        addGoods(state, arr) {
            state.goods.push(...arr);
        },
        setGoodsLoading(state, value) {
            state.goodsLoading = value;
        },
    },
    actions: {
        async getChannels({ commit }) {
            const { data: arr } = await getChannels();
            // this.channels = data;
            commit("setChannels", arr);
        },
        async getGoodsByPage({ commit, state, getters }, page) {
            // state.goodsLoading = true
            commit("setGoodsLoading", true);

            // 数据还没有的时候联网获取
            const { data: arr } = await goodsApi.getGoodsByPage(page);
            // this.goods.push(...arr);
            commit("addGoods", arr);

            // state.goodsLoading = false
            commit("setGoodsLoading", false);
        },
    },
    // plugins: [persistedState()],
    modules: {
        user
    },
});
